package top.iszsq.config.binds;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 自定义LocalDateTime web参数转换
 * @author zsq
 * @date 2021/7/1 11:53
 **/
public class LocalDateTimeEditor extends PropertyEditorSupport {

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @see PropertyEditorSupport#setAsText(String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String dateStr = text;

        LocalDateTime parse = null;
        if (dateStr != null && !"".equals(dateStr.trim())) {
            try {
                parse = LocalDateTime.parse(dateStr);
            } catch (Exception e) {
                parse = LocalDateTime.parse(dateStr, dateFormatter);
            }
        }
        setValue(parse);
    }

    @Override
    public String getAsText() {
        Object value = this.getValue();
        if (value == null) {
            return null;
        }
        String formatText = ((LocalDateTime)value).format(dateFormatter);

        return formatText;
    }
}
